<template>
  <el-col class="container">
    <SubHeader style="position: relative" >
      <template v-slot> 管理本店所有优惠券

          <el-input
              v-model="couponNum"
              placeholder="查询优惠券标题"
              style="position:relative;margin-left:300px; width:200px"
              clearable
          ></el-input>

        <el-button type="primary" style="position:relative;margin-bottom: 50px;margin-left: 10px"  @click="search">
          查询
        </el-button>

        <el-button style="position:relative;" type="primary" @click="addCoupon">增加新优惠券</el-button>
        <el-button style="position:relative;" type="primary" @click="refreshTable">刷新</el-button>

      </template>
    </SubHeader>

    <el-form @submit.native.prevent>

    </el-form>

    <el-table :data="tableData" style="margin-top: 20px" border stripe>
      <el-table-column
          prop="index"
          label="序号"
          width="50px"
          align="center"
      ></el-table-column>

      <el-table-column
          prop="couponTitle"
          label="优惠券标题"
          width="120px"
          align="center"
      ></el-table-column>

      <el-table-column
          prop="couponPrice"
          sortable
          label="面值"
          width="110px"
          align="center"
      >
      </el-table-column>



      <el-table-column
          prop="couponRemainCount"
          label="剩余数量"
          width="85px"
          align="center" >
      </el-table-column>


      <el-table-column
          prop="couponMinPrice"
          sortable
          label="最低消费"
          width="110px"
          align="center"
      >
      </el-table-column>


      <el-table-column
          prop="couponStartTime"
          sortable
          label="优惠券开始时间"
          width="160px"
          align="center"
      >
      </el-table-column>

      <el-table-column
          prop="couponEndTime"
          sortable
          label="优惠券结束时间"
          width="160px"
          align="center"
      >
      </el-table-column>


      <el-table-column
          prop="couponTime"
          sortable
          label="有效期"
          width="110px"
          align="center"
      >
      </el-table-column>



      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="scope">
          <el-button
              @click="handleEdit(scope.row)"
              type="primary"
              icon="el-icon-edit"
              circle
              size="mini"
          ></el-button>


          <el-tooltip content="查看优惠券详细信息" placement="top">
            <el-button
                @click="showSale(scope.row)"
                type="primary"
                icon="el-icon-info"
                circle
                size="mini"
            ></el-button>
          </el-tooltip>

          <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              size="mini"
              @click.native.prevent="deleteRow(scope.$index, tableData)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[5, 10, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 10px"
    >
    </el-pagination>

    <!-- 修改商品弹出 -->
    <el-dialog
        title="填写优惠券信息"
        :visible.sync="dialogFormVisible"
        class="add"
    >
      <el-form ref="form" :model="form" label-width="60px">
        <el-row type="flex">
          <el-col>
            <el-form-item label="标题"   style="margin-bottom: 7px" required="true">
              <el-input  placeholder="输入优惠券标题"
                  v-model="form.productName"
                  style="width: 200px"
              ></el-input>
            </el-form-item>

             <el-form-item label="面值:" style="margin-bottom: 7px" required="true">
              <el-input  placeholder="输入优惠券面值" v-model="form.couponPrice" style="width: 200px"></el-input>
            </el-form-item>

          </el-col>



          <el-col>
            <el-form-item  label="条件:" style="margin-bottom: 7px" required="true">
              <el-input placeholder="输入最低消费" v-model="form.discount" style="width: 200px"></el-input>
            </el-form-item>
            <el-form-item  label="时间:" style="margin-bottom: 7px" required="true">
              <el-input placeholder="输入优惠券有效时间" v-model="form.sold" style="width: 200px"></el-input>
            </el-form-item>

            <el-form-item  label="数量:" style="margin-bottom: 7px" required="true">
              <el-input placeholder="发布优惠券数量" v-model="form.left" style="width: 200px"></el-input>
            </el-form-item>

          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>


  </el-col>
</template>

<script>
import request from '../../../utils/request'
const SubHeader = () => import('../../components/SubHeader.vue')

export default {
  components: {
    SubHeader
  },
  name: 'Home',
  data() {
    return {
      form: {},
      dialogFormVisible: false,
      dialogFormVisible2: false,
      // pageSize是表示一页最多可以装几条数据
      pageSize: 5,
      // 表示请求第几页数据
      pageNum: 1,
      // 查询关键字
      couponNum: "",
      // 总共几条数据
      total: "",
      index: "",
      tableData: [],
      options: [],
      value: '',
      timer: null,
      sId: sessionStorage.getItem('shopId')
    }
  },
  created() {
    this.load()
    request
        .get('/category/all')
        .then((res) => {
          this.options = []
          res.forEach((c) => {
            let [value, label] = [c.categoryId, c.categoryName]
            let category = { value, label }
            this.options.push(category)
          })
        })
        .catch((err) => {
          console.log(err)
        })
  },
  methods: {
    // 刷新表格
    refreshTable() {
      this.load()
      this.$message({
        message: '刷新成功！',
        type: 'success'
      })
    },
    // 删除
   /* async deleteRow(index, rows) {
      await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(() => {
            let deleteId = rows[index].productId
            rows.splice(index, 1)
            request.delete('/product/' + deleteId).then((res) => {
              if (res.code === '0') {
                this.$message({
                  message: '删除成功！',
                  type: 'success'
                })
              }
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      this.refreshTable()
    },*/
    // 编辑
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogFormVisible = true

      this.$nextTick(() => {
        this.$refs['upload'].clearFiles()
      })
    },
    // 查看销售信息
    showSale(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogFormVisible2 = true
    },
    search() {
      this.load()
      /*--------------------------------------------*/
    },
    handleTotalChange(val) {
      // console.log(`总共 ${val} 条`)
      this.total = val
      this.load()
    },
    /*-----------------------------------------------*/
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.load()
    },
    /*-------------------------------------------------*/

    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.pageNum = val
      this.load()
    },
    // 加载表格数据------------------------------------------------------------
    load() {
      let sId = sessionStorage.getItem('shopId')
      request
          .get('/coupon/shop', {
            params: {
              total: this.total,
              pageNum: this.pageNum,
              pageSize: this.pageSize,
              tableData: this.tableData,
              key: this.key,
             ownerId: sId
            }
          })
          .then((res) => {
            this.total = res.data.total
            this.tableData = []
            res.data.data.forEach((e, i) => {
              e.index = i + 1
              this.tableData.push(e)
            })
          })
    },
    addCoupon() {
      this.dialogFormVisible = true
      this.form = {}
      // 清空原文件内容
      this.$nextTick(() => {
        this.$refs['upload'].clearFiles()
      })
    },
    uploadSuccess(res) {
      // console.log(res)
      if (res.code == '0') {
        this.form.imgSrc = res.data
        this.$message({
          message: '恭喜你,上传成功!',
          type: 'success',
        })
        this.load
      }
      else {
        this.dialogFormVisible = false
        this.$message({
          message: res.msg,
          type: 'err',
        })
      }
    },
    getCategory(val) {
      let res = ''
      this.options.some((item) => {
        if (val == item.value) {
          res = item.label
          return true
        }
      })
      return res
    },
    getCouponInfo() {
      return request.get('/shop/' + this.sId).then((res) => {
        return res
      })
    },
    save() {
      // console.log(this.form)
      if (this.form.productId) {
        // 若此调数据有id，则进行更新操作，同步数据库，进行PUT请求
        request
            .put('/coupon', this.form)
            .then((res) => {
              if (res.code === '0') {
                this.dialogFormVisible = false
                this.$message({
                  message: '恭喜你，修改成功！',
                  type: 'success'
                })
              } else {
                this.$message({
                  message: '修改失败，请联系管理员！',
                  type: 'failed'
                })
              }
            })
            .catch((err) => {
              console.log(err)
            })
            .then(() => {
              // 刷新表格数据
              this.load()
            })
      } else {
        this. getCouponInfo().then((res1) => {
          this.form.shopId = res1.data.shopId
          this.form.sold = Math.round(Math.random() * (500 - 100)) + 100
          request
              .post('/coupon', this.form)
              .then((res) => {
                if (res.code === '0') {
                  this.$message({
                    message: res.msg,
                    type: 'success',
                    duration: 1000
                  })
                  clearTimeout(this.timer)
                  this.timer = setTimeout(() => {
                    this.dialogFormVisible = false
                    this.load()
                  }, 1000)
                }
              })
              .catch((err) => {
                console.log(err)
              })
              .then(() => {
                // 刷新表格数据
                this.load()
              })
        })
      }
    }
  }
}
</script>

<style>
.container {
  padding: 20px;
  box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px,
  rgba(60, 64, 67, 0.15) 0px 2px 6px 2px;
  border-radius: 5px;
}
</style>